<?php

namespace App\Admin\Controllers;

use App\Admin\Extensions\Tools\CheckPost;
use App\Facades\AdminC;
use App\Http\Controllers\Controller;
use App\Models\Article;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Support\Facades\Input;
use App\Models\Category;

class ArticleController extends Controller
{
    use ModelForm;

    /**
     *  首页
     */
    public function index()
    {
        return AdminC::content(function(Content $content){
            $content->header('文章视频');
            $content->description('列表');
            $content->body($this->grid());
        });
    }

    protected function grid()
    {   
        return AdminC::grid(Article::class, function(Grid $grid) {
            $grid->filter(function($filter){
                $filter->like('title','标题');
                $filter->like('from_author','来源作者');
                $category = (new Category())->byTree();
                $filter->equal('cate_id','分类')->select($category);
                $model = new Article();
                $filter->equal('status','状态')->select($model->status_arr);
            });
            if(!Input::get('_sort')){
                $grid->model()->orderBy('id','desc');
            }
            $grid->id('Id')->sortable()->style('width:5%;');
            $grid->pic('图片')->display(function($pic){
                $pic = explode(',', $pic);
                $img = '';
                foreach ($pic as $v) {
                    $img .= '<img src="'.$v.'" alt=""  width="120" height="60">';
                }
                return $img;

            })->style('width:12%;');
            $grid->title('标题')->style('width:15%;');
            $grid->intro('描述')->style('width:20%;');
            $grid->source_link('播放地址')->display(function($source_link) {
                return "<a href='article/video?source=".base64_encode($source_link)."&cate=".$this->from_cateid."&id=".$this->id."' class='btn btn-default' target='_blank'>播放</a>";
            })->style('width:5%;');
            $grid->cate_id('所属分类id')->display(function($cate_id){
                $cate_info = (new Article())->getCateName($cate_id);
                if($cate_info)
                    return $cate_info->name."/".$cate_id;
                return $cate_id;
            })->style('width:10%;');
            $grid->status('状态')->display(function($status){
                if($status == 1) {
                    return '<span style="color: green; font-weight: 700;">'.$this->status_arr[$status].'</span>';
                }elseif ($status == 2) {
                    return '<span style="color: red; font-weight: 700;">'.$this->status_arr[$status].'</span>';
                }
                return $this->status_arr[$status];
            })->style('width:5%;');
            $grid->views('浏览量')->style('width:5%;');
            $grid->zan('点赞数')->style('width:5%;');
            $grid->comments_num('评论数')->style('width:5%;');
            $grid->from_author('来源作者')->style('width:5%');
            $grid->created_at('创建时间');

            $grid->tools(function($tools){
               $tools->batch(function($batch){
                    $batch->add('通过审核', new CheckPost(1));
                    $batch->add('不通过审核', new CheckPost(0));
               });
            });

            $grid->disableExport();
        });
    }

    public function create()
    {
        return AdminC::content(function(Content $content){
            $content->header('文章视频');
            $content->description('新增');
            $content->body($this->form());
        });
    }

    public function edit($id)
    {
        return AdminC::content(function(Content $content) use($id) {
            $content->header('文章视频');
            $content->description('编辑');
            $content->body($this->form()->edit($id));
        });
    }

    protected function form()
    {
        return AdminC::form(Article::class, function (Form $form) {
            $form->display('id', 'ID');
            $form->text('title','标题');
            $form->text('intro','描述');
            $form->image('pic','图片');
            $form->text('source_link','存储地址');
            $form->wangeditor('content','内容');
            $category = (new Category())->byTree();
            $form->select('cate_id','所属分类')->options($category);
            $form->text('views','浏览量')->default(0);
            $form->select('status', '状态')->options($form->model()->status_arr);
            $form->display('created_at', '创建时间');
            $form->display('updated_at', '更新时间');
        });
    }

    /**
     * 重写删除操作
     * @param $id  主键id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        if ($this->form()->destroy($id)) {
            $ids = explode(',',$id);
            foreach ($ids as $v_id) {
                //同时删除本地文件
                $article_info = Article::find($v_id);
                $path = public_path();
                try {
                    $file_path = $path.'/'.$article_info->source_link;
                    @unlink($file_path);
                }catch (\Exception $e) {

                }
            }

            return response()->json([
                'status'  => true,
                'message' => trans('admin.delete_succeeded'),
            ]);
        } else {
            return response()->json([
                'status'  => false,
                'message' => trans('admin.delete_failed'),
            ]);
        }
    }

    /**
     *  播放视频
     */
    public function video()
    {
        if(!Input::has('source') || empty(Input::get('source'))){
            abort(404);
        }

        $input = Input::all();
        $source = base64_decode($input['source']);
        if($input['cate'] == 1) {
            $source = $this->ixiguaHandle($source);
        }
        preg_match('/(http|https)/',$source, $arr);
        if(empty($arr)) {
            $source = '/'.$source;
        }
//        dd($source);
        return view('admin.article_video', ['source'=>$source]);
    }

    protected function ixiguaHandle($videoid)
    {
        $s = getUrl($videoid);
        $json = $this->requestUrl($s);
        $arr = json_decode($json, 1);
        $main_url = $arr['data']['video_list']['video_1']['main_url'];
        $main_url = base64_decode($main_url);

        return $main_url;
    }

    protected function requestUrl($URL)
    {
        $c = curl_init();
        curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
        //curl_setopt($c, CURLOPT_HEADER, 1);//输出远程服务器的header信息
        curl_setopt($c, CURLOPT_USERAGENT, 'User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 MicroMessenger/6.5.2.501 NetType/WIFI WindowsWechat');
        curl_setopt($c, CURLOPT_URL, $URL);
        $contents = curl_exec($c);
        curl_close($c);
        if ($contents) {
            return $contents;
        } else {
            return FALSE;
        }
    }

    //checkPost 批量验证操作
    public function checkPost()
    {
        $input = Input::all();
        if(isset($input['ids']) && isset($input['action'])) {
            $res = (new Article())->check($input['ids'], $input['action']);
            if($res) {
                return response()->json(['code'=>1, 'msg'=>'成功']);
            }else{
                return response()->json(['code'=>0, 'msg'=>'失败']);
            }
        }else{
            return response()->json(['code'=>0, 'msg'=>'参数错误']);
        }
    }


}
